<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm
          :fieldList="fieldList"
          :formOption="optionsDataAll"
          :formData="form"
        >
          <template #create_user="{ value, input }">
            <VCascader
              :model-value="value"
              @update:model-value="input"
              collapse-tags
              class="w-[200px]"
              placeholder="创建人"
            />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <VActionBar :actions="actions" />
      </template>
      <template #time_limit="{ row }">
        <div>{{ row?.min_time_limit}}-{{row?.max_time_limit}}天</div>
      </template>
    </VTable>
    <Log
      dialog
      v-model="logVisible"
      :autoLoad="false"
      tag="channel.transport-cost"
      :business_id="logId"
      @close="logId = ''"
    />
    <add
      v-model="visible"
      :channelId="channelId"
      :id="addId"
      :options="optionsDataAll"
      :billingType="billingType"
      :currency="channel_currency"
      @close="addId = ''"
      @refresh="query"
    />
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import XForm from "@/components/XForm/index.vue";
import { useEnumSelect } from "@/hooks/useEnumSelect.js";
import { getChannelList, getCountry } from "@/api/index.js";
import { getLogisticsAttr } from "@/api/public.js";
import Log from "@/components/Log/index.vue";
import add from "./add/index.vue";
import {
  statusTransportCost,
  deleteTransportCost,
  transportCostFile,
  channelCtcOpts,
  transportCostList,
} from "./api/index.js";
import { statusMap } from "@/data";
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

const optionsData = ref({});
const optionsData2 = ref({});
const { options: optionsData1 } = useEnumSelect({
  params: ["surcharge_rule_type", "channel_calc_fuel_mode", "ctc_ests_state"],
});
const channelOpts = async (channel_id) => {
  const { data } = await channelCtcOpts({ channel_id });
  optionsData2.value = data;
};
const optionsDataAll = computed(() =>
  Object.assign({}, optionsData.value, optionsData1.value, optionsData2.value, {
    symbol: [
      { label: "<", value: 3 },
      { label: "<=", value: 4 },
    ],
  })
);
// const getCostFile = async (channel_id) => {
//   try {
//     const { data } = await transportCostFile({ channel_id });
//     optionsData.value.file_name_data = data
//       ?.filter((n) => n.file_name)
//       ?.map((n) => ({ name: n.file_name, file_md5: n.file_md5 }));
//   } catch (e) {
//     console.error(e);
//   }
// };
const getChannel = async () => {
  const { data } = await getChannelList();
  optionsData.value.channel = data;
};

const getCountryList = async () => {
  const { data } = await getCountry();
  optionsData.value.country = data;
};

const getLogistics = async () => {
  const { data } = await getLogisticsAttr();
  optionsData.value.logisticsAttributes = data;
};

// watchEffect(async () => {
//   const { id } = route.query || {};
//   if (id) {
//     await nextTick();
//     const form = tableRef.value.getForm();
//     tableRef.value.setForm({
//       ...form,
//       channel_id: id
//     });
//     query();
//   }
// });
// 查询
const query = () => {
  tableRef?.value.query();
};
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {},
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    { fixed: "left", width: 80, title: "编号", field: "id" },
    { fixed: "left", title: "运价文件名", minWidth: 200, field: "v_file_name" },
    { title: "生效状态", width: 100, field: "ests_state" },
    { title: "物流商", width: 240, field: "logistics_name" },
    { title: "中文渠道名称", width: 200, field: "channel_name" },
    { title: "计费类型", width: 200, field: "billing_type_text" },
    { title: "运输类型", width: 200, field: "transport_type_text" },
    { title: "始发站", width: 200, field: "shipping_address" },
    { title: "目的地", width: 200, field: "arrival_address" },
    { title: "目的地二字码", width: 200, field: "destination_country" },
    { title: "区域", width: 200, field: "regions" },
    { title: "货物类型", width: 200, field: "goods_attrs_text" },
    {
      title: "时效",
      width: 200,
      field: "time_limit",
      slots: { default: "time_limit" },
    },
    { title: "抛重计算因子", width: 200, field: "count_reason" },
    { title: "版本时间", width: 350, field: "v_time" },
    { title: "系统生效时间", width: 350, field: "sys_ests_time" },
    { title: "备注", width: 200, field: "remark" },
    {
      title: "操作",
      minWidth: 200,
      fixed: "right",
      align: "center",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-button link type="primary" onClick={() => handleEdit(row)}>
                查看
              </el-button>
              <el-button
                link
                type={row.status === 0 ? "primary" : "danger"}
                onClick={() => handleStatus(row)}
              >
                {{ 0: "启用", 1: "禁用" }[row.status]}
              </el-button>
              <el-button link type="primary" onClick={() => handleLog(row)}>
                日志
              </el-button>
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        let formValue = form;
        const { ests_state, channel_name } = form;
        if (!ests_state || !channel_name) {
          tableRef.value.setForm({
            ...form,
            ests_state: "ING",
            channel_name: channelName.value,
            channel_id: channelId.value,
          });
          const formData = tableRef.value.getForm();
          formValue = formData;
        }
        return transportCostList({ ...formValue, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});
const channel_currency = ref();
const channelId = ref();
const channelName = ref();
onMounted(async () => {
  await getCountryList();
  await getLogistics();
  await getChannel();
  const { id, currency } = route.query;
  channel_currency.value = currency;
  channelId.value = id;
  await channelOpts(id);
  // await getCostFile(id);
  let channel = optionsData.value.channel?.find(
    (n) => n.id == id
  )?.channel_name;
  channelName.value = channel;
  const form = tableRef.value.getForm();
  tableRef.value.setForm({
    ...form,
    channel_id: id,
    channel_name: channel,
    ests_state: "ING",
  });
  query();
});
const handleChannel = async (e) => {
  let item = optionsData.value.channel.find((n) => n.channel_name == e);
  router.push({
    path: `/logistics-settings/channel/transport-cost`,
    query: { id: item.id, currency: item?.currency || "CNY" },
  });
  channelId.value = item.id;
  channelName.value = e;
  channel_currency.value = item.currency;
  await channelOpts(channelId.value);
  // await getCostFile(channelId.value);
  const form = tableRef.value.getForm();
  tableRef.value.setForm({
    ...form,
    channel_id: channelId.value,
    channel_name: e,
    file_md5: "",
  });
  query();
};
const visible = ref(false);
const addId = ref(null);
const billingType = ref();
const handleEdit = (row) => {
  addId.value = row.id;
  billingType.value = row.billing_type;
  visible.value = true;
};
const logVisible = ref(false);
const logId = ref("");
const handleLog = (item) => {
  logId.value = item.id;
  logVisible.value = true;
};

const publicStyle = { style: { width: "240px" } };
const fieldList = [
  {
    field: "channel_name",
    type: "select",
    originOption: "channel",
    ...publicStyle,
    options: {
      placeholder: "渠道名称",
      labelKey: "channel_name",
      valueKey: "channel_name",
    },
    itemProps: {
      onChange: (e) => handleChannel(e),
    },
  },
  {
    field: "goods_attrs",
    type: "select",
    multiple: true,
    originOption: "logisticsAttributes",
    options: {
      placeholder: "货物类型",
    },
    ...publicStyle,
  },
  {
    field: "shipping_address",
    type: "input",
    placeholder: "始发站",
    ...publicStyle,
  },
  {
    field: "destination_country",
    type: "select",
    originOption: "country",
    multiple: true,
    options: {
      placeholder: "目的地",
    },
  },
  {
    field: "file_md5",
    type: "select",
    originOption: "ctc_file_opts",
    options: {
      placeholder: "运价文件名",
    },
    ...publicStyle,
  },
  {
    field: "ests_state",
    type: "select",
    originOption: "ctc_ests_state",
    options: {
      placeholder: "生效状态",
    },
    style: { width: "140px" },
  },
  {
    field: "v_times",
    type: "select",
    originOption: "v_time_opts",
    options: {
      placeholder: "版本时间",
    },
    ...publicStyle,
  },
  {
    field: "sys_ests_times",
    type: "select",
    originOption: "sys_ests_time_opts",
    options: {
      placeholder: "系统生效时间",
    },
    ...publicStyle,
  },
];
</script>
